<?php

namespace app\admin\controller;

use addons\shopro\model\Breed;
use addons\shopro\model\Cats;
use app\admin\model\AdminLog;
use app\api\controller\BaofuPay;
use app\api\controller\Demo;
use app\common\controller\Backend;
use app\common\model\UserBaofuBank;
use baofu\Baofu;
use think\Db;

/**
 * 咪猫订单-周期付
 *
 * @icon fa fa-circle-o
 */
class CatOrder extends Backend
{

    /**
     * CatOrder模型对象
     * @var \app\admin\model\CatOrder
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\CatOrder;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("payTypeList", $this->model->getPayTypeList());
    }


    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams('cat_order.id,cat_order.order_sn', true);
        $list = $this->model
            ->with(['user'])
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);

        foreach ($list as $row) {
            //显示关联表中的employee_name字段
            $row->getRelation('user')->visible(['username']);
            $row->getRelation('user')->visible(['mobile']);
        }


        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }


    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->with(['user', 'cat'])->find($ids);
        $row['breed_name']=Breed::where('id',$row->cat->pid)->value('name');
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }
    //解约
    public function unsign($ids = null)
    {
        $row = $this->model->with(['user', 'cat'])->find($ids);

        if ($row == null) {
            $this->error('签约信息未找到');
        }
        $insert = [
            'title' => '商户解约解约',
            'content' => '商户解约',
            'url' => substr(request()->url(), 0, 1500),
            'admin_id' => 1,
            'username' => '用户解约',
            'useragent' => substr(request()->server('HTTP_USER_AGENT'), 0, 255),
            'ip' => request()->ip()
        ];
        AdminLog::insert($insert);
        //解约
        $this->model->where('id', $row->id)->update(['status' => 3, 'unsign' => 2, 'updatetime' => time()]);//1用户解约，2商户解约

        //检查签约信息
        $bank = Db::name('user_baofu_bank')->where('order_id',$ids)->where('status',2)->find();
        if($bank){
            $config = Db::name('config')->where('group', 'baofu')->column('value', 'name');

            //银行卡解约
            \think\Loader::import("\baofu\baofu",EXTEND_PATH);
            $baofu = new \baofu\Baofu($config);
            $baofu->ABolishBind($row['protocol_no'],$row->user_id);

            //修改绑卡状态
            (new UserBaofuBank())->where('protocol_no', $row['protocol_no'])->update(['updatetime' => time(), 'status' => 3, 'unbindtime' => time()]);

//            $cats = Cats::where('id',$row['cat_id'])->find();
//            if($cats){
//                \addons\shopro\model\User::money(-$cats['integral'], $bank['user_id'], 'cats_recharge', $row['cat_id'], '猫咪已解约,扣除奖励积分'.$cats['integral']);
//            }
        }

        $this->success('解约成功');
    }
    //退款
    public function refund($ids = null)
    {
        $row = $this->model->with(['user', 'cat'])->find($ids);

        //查看付款记录
        $pay = Db::name('baofu_pay')->where('order_id',$row->id)->where('status',1)->order('id desc')->find();
        if($pay == null){
            $this->error('订单付款信息为空');
        }

        $config = Db::name('config')->where('group','baofu_tui')->column('value','name');
        \think\Loader::import("\baofu\baofu",EXTEND_PATH);
        $baofu = new \baofu\Refund($config);
        $transSerialNo = $baofu->getTransSerialNo();
        
        $result = $baofu->action($pay['trans_id'],bcmul($pay['txn_amt'],100),$transSerialNo);

        $paylog = [
            'user_id' => $row['user_id'],
            'order_id' => $row['id'],
            'trans_id' => $transSerialNo,
            'type' => 'refund',
            'memo' => '订单退款',
            'txn_amt' => $pay['txn_amt'],
            'cycle' => $pay['cycle'],
            'createtime' => time(),
            'notify' => is_array($result['notify']) ? json_encode($result['notify']) : $result['notify'],
        ];

        if($result['code'] == 0){
            $paylog['status'] = 2;
            Db::name('baofu_pay')->insert($paylog);
            $this->error('退款失败');
        }

        if($result['code'] == 200){
            //退款成功
            $this->model->where('id', $ids)->update(['status' => 5, 'trade_no' => $transSerialNo, 'refundtime' => time()]);
            $paylog['status'] = 1;
            Db::name('baofu_pay')->insert($paylog);

            //修改绑卡状态
            (new UserBaofuBank())->where('protocol_no', $row['protocol_no'])->update(['updatetime' => time(), 'status' => 3, 'unbindtime' => time()]);

            $this->success('退款成功');
        }elseif($result['code'] == 201){
            $paylog['status'] = 3;
            Db::name('baofu_pay')->insert($paylog);
            \think\Queue::later(10, '\addons\shopro\job\OrderAutoOper@baofuQueryRefund', ['refund_no' => $transSerialNo], 'shopro');
            $this->success('退款中');
        }else{
            $paylog['status'] = 2;
            Db::name('baofu_pay')->insert($paylog);
            $this->error('退款失败');
        }
    }

    //延期扣款
    public function yanqi($ids = null)
    {
        $row = $this->model->find($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $row->dangqian = $row->total_cycle - $row->remaining_cycle;
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }

        if($row->remaining_cycle == 0 || !in_array($row->status,[1,4])){
            $this->error('此订单不需要延期扣款');
        }

        if (false === $this->request->isPost()) {

            $this->view->assign('row', $row);

            if($row->paytime == null){
                $mindate = strtotime('+1 day',strtotime($row->deduction_time));
            }else{
                $mindate = strtotime('+1 day',$row->paytime);
            }
            $maxdate = strtotime('+15 day',$mindate);
            $this->view->assign('mindate', date('Y-m-d',$mindate));
            $this->view->assign('maxdate', date('Y-m-d',$maxdate));
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //周期扣款时间
            $yanqi_time = strtotime($params['yanqi_day'].' 9:0:0');
            //$yanqi_time = time() + 60 * 30;
            \think\Queue::later($yanqi_time - time(), '\addons\shopro\job\OrderAutoOper@baofuPay', ['order' => $row], 'shopro');


            //短信通知时间
            $smstime = strtotime("-3 days", $yanqi_time);
            $time = ($smstime > time()) ? ($smstime - time()) : 5;
            \think\Queue::later($time, '\addons\shopro\job\OrderSms@sending_sms', ['order' => $row], 'shopro');

            $params['yanqi_day'] = $yanqi_time;
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }
}
